package com.plugin.manage.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * 
 * @author mark
 * @date 2025-07-23
 */
@Component
public class JwtTokenUtil {

    // JWT密钥（生产环境应该从配置文件读取）
    @Value("${jwt.secret:K7mN9pQ2xR8vW3zA6bE4yT1uI5oP7sL0mF2nH8jK9wX1cV4bN6zQ3yE7rT0uI5oP}")
    private String secret;

    // Token过期时间（24小时）
    @Value("${jwt.expiration:86400}")
    private Long expiration;

    /**
     * 生成JWT Token
     */
    public String generateToken(JwtPayload payload) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", payload.getUserId());
        claims.put("loginTime", payload.getLoginTime());
        claims.put("roleId", payload.getRoleId());
        claims.put("expiredTime", payload.getExpiredTime());
        return createToken(claims, payload.getUsername());
    }

    /**
     * 创建Token
     */
    private String createToken(Map<String, Object> claims, String subject) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expiration * 1000);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();
    }

    /**
     * 从Token中获取用户名
     */
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    /**
     * 从Token中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("userId", Long.class));
    }

    /**
     * 从Token中获取用户角色
     */
    public String getRoleFromToken(String token) {
        return getClaimFromToken(token, claims -> {
            Object roleId = claims.get("roleId");
            return roleId != null ? roleId.toString() : null;
        });
    }

    /**
     * 从Token中获取过期时间
     */
    public Date getExpirationFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    /**
     * 从Token中获取指定声明
     */
    public <T> T getClaimFromToken(String token, ClaimsResolver<T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.resolve(claims);
    }

    /**
     * 从Token中获取所有声明
     */
    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 检查Token是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            final Date expiration = getExpirationFromToken(token);
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 验证Token
     */
    public Boolean validateToken(String token, String username) {
        try {
            final String tokenUsername = getUsernameFromToken(token);
            return (username.equals(tokenUsername) && !isTokenExpired(token));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取签名密钥
     */
    private SecretKey getSigningKey() {
        // 确保密钥长度至少64字节以支持HS512算法
        String keyString = secret;
        if (keyString.length() < 64) {
            // 如果密钥长度不足，进行填充
            StringBuilder sb = new StringBuilder(keyString);
            while (sb.length() < 64) {
                sb.append(keyString);
            }
            keyString = sb.substring(0, 64);
        }
        return Keys.hmacShaKeyFor(keyString.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 声明解析器接口
     */
    @FunctionalInterface
    public interface ClaimsResolver<T> {
        T resolve(Claims claims);
    }
}
